<?php
namespace Sdk\Message\Adapter\ImMessage;

use Marmot\Core;
use Marmot\Interfaces\INull;
use Marmot\Interfaces\IRestfulTranslator;
use Sdk\Common\Adapter\CommonRestfulAdapter;

use Sdk\Common\Adapter\Traits\MapErrorsTrait;
use Sdk\Common\Adapter\Traits\FetchAbleRestfulAdapterTrait;

use Sdk\Message\Model\ImMessage;
use Sdk\Message\Model\NullImMessage;
use Sdk\Message\Translator\ImMessageRestfulTranslator;

class ImMessageRestfulAdapter extends CommonRestfulAdapter implements IImMessageAdapter
{
    use FetchAbleRestfulAdapterTrait,
        MapErrorsTrait;
        
    const MAP_ERROR = array(
        100002 => array(
            'internalMessage' => RESOURCE_CAN_NOT_MODIFY
        )
    );
    
    const SCENARIOS = [
        'IM_MESSAGE_LIST'=>[
            'fields' => [],
            'include' => ''
        ],
        'IM_MESSAGE_FETCH_ONE'=>[
            'fields'=>[],
            'include'=>''
        ]
    ];

    public function __construct(string $baseurl = '', array $headers = [])
    {
        parent::__construct(
            new ImMessageRestfulTranslator(),
            'messages/im',
            $baseurl,
            $headers
        );
    }

    protected function getNullObject() : INull
    {
        return NullImMessage::getInstance();
    }

    protected function getAlonePossessMapErrors() : array
    {
        return self::MAP_ERROR;
    }

    public function scenario($scenario) : void
    {
        $this->scenario = isset(self::SCENARIOS[$scenario]) ? self::SCENARIOS[$scenario] : array();
    }

    public function read(ImMessage $imMessage, array $keys) : bool
    {
        $data = $this->getTranslator()->objectToArray($imMessage, $keys);

        $this->patch(
            $this->getResource().'/'.$imMessage->getId().'/read',
            $data
        );
        
        if ($this->isSuccess()) {
            $this->translateToObject($imMessage);
            return true;
        }

        return false;
    }
}
